package com.csproj.system.resource;

import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.service.DictionaryService;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import com.csproj.system.service.dto.DictionaryDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.codahale.metrics.annotation.Timed;

/**
 * REST controller for managing Dictionary.
 */
@RestController
@RequestMapping("/api/siiat/v1/")
public class DictionaryResource {

    private final Logger log = LoggerFactory.getLogger(DictionaryResource.class);

    private static final String ENTITY_NAME = "dictionary";

    private final DictionaryService dictionaryService;
    private final UserInfoService userInfoService;
    private final SysLogsService sysLogsService;


    public DictionaryResource(DictionaryService dictionaryService,
                              UserInfoService userInfoService,
                              SysLogsService sysLogsService) {
        this.dictionaryService = dictionaryService;
        this.userInfoService = userInfoService;
        this.sysLogsService = sysLogsService;
    }

    /**
     * POST  /dictionaries : Create a new dictionary.
     *
     * @param dictionaryDTO the dictionaryDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new dictionaryDTO, or with status 400 (Bad Request) if the dictionary has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/dictionaries")
    @Timed
    public BaseDTO createDictionary(@RequestBody DictionaryDTO dictionaryDTO) throws URISyntaxException {
        log.debug("REST request to save Dictionary : {}", dictionaryDTO);
        if (dictionaryDTO.getId() != null) {
            return BaseDTO.createBaseDTO().setSuccess(false).setMessage("duplicate_name");
        }
        DictionaryDTO result = dictionaryService.save(dictionaryDTO);
        return BaseDTO.createBaseDTO(result);
    }

    /**
     * PUT  /dictionaries : Updates an existing dictionary.
     *
     * @param dictionaryDTO the dictionaryDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated dictionaryDTO,
     * or with status 400 (Bad Request) if the dictionaryDTO is not valid,
     * or with status 500 (Internal Server Error) if the dictionaryDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/dictionaries/{id}")
    @Timed
    public BaseDTO updateDictionary( @PathVariable("id") String id,@RequestBody DictionaryDTO dictionaryDTO) throws URISyntaxException {
        log.debug("REST request to update Dictionary : {}", dictionaryDTO);
        dictionaryDTO.setId(id);
        DictionaryDTO result = dictionaryService.save(dictionaryDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_save_config","");
        return BaseDTO.createBaseDTO(result);
    }

    /**
     * GET  /dictionaries : get all the dictionaries(获取所有的字典信息（ ）).
     *
     * @return the ResponseEntity with status 200 (OK) and the list of dictionaries in body
     */
    @GetMapping("/dictionaries")
    @Timed
    public BaseDTO getAllDictionaries(@RequestParam(value = "pageNumber",required = false) Integer pageNumber,
    		@RequestParam(value = "dictionaryType",required = false) String dictionaryType ,
    		@RequestParam(value = "dictionaryName",required = false) String dictionaryName ,
    		@RequestParam(value = "description",required = false) String description ) {
        log.debug("REST request to get all Dictionaries");
        String hsql = "";
        Map<String,Object> mapParas = new HashMap<>();
        if(StringUtils.isNotBlank(dictionaryType)){
        	hsql += " and dt.dictionaryType like :dictionaryType ";
        	mapParas.put("dictionaryType", "%"+dictionaryType.trim()+"%");
        }
        if(StringUtils.isNotBlank(dictionaryName)) {
        	hsql += " and dt.dictionaryName like :dictionaryName ";
        	mapParas.put("dictionaryName", "%"+dictionaryName.trim()+"%");
        }
        if(StringUtils.isNotBlank(description)) {
        	hsql += " and dt.description like :description ";
        	mapParas.put("description", "%"+description.trim()+"%");
        }

        if(pageNumber==null || pageNumber == 0) {
        	List<DictionaryDTO> result = dictionaryService.findAll();
        	return BaseDTO.createBaseDTOByFieldList(result);
        }else {
        	Pageable pageable =  PageableTools.basicPage(pageNumber,"creationTime");
        	return  dictionaryService.findPageList(pageable,hsql,mapParas) ;

        }
    }

    /**
     * GET  /dictionaries/dictionaryType/:dictionaryType : get dictionaryType the dictionaries(根据类型获取所有的字典信息（ ）).
     *
     * @return the ResponseEntity with status 200 (OK) and the list of dictionaries in body
     */
    @GetMapping("/dictionaries/dictionaryType/{dictionaryType}")
    @Timed
    public BaseDTO getDictionaryByDictionaryType(@PathVariable String dictionaryType) {
        log.debug("REST request to get dictionaryType Dictionaries");
        List<DictionaryDTO> dictionaryDTOList = dictionaryService.getDictListByType(dictionaryType);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":get_dictionary_by_dictionary_type","");
        return BaseDTO.createBaseDTOByFieldList(dictionaryDTOList);
    }

    /**
     * GET  /dictionaries/:id : get the "id" dictionary.
     *
     * @param id the id of the dictionaryDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the dictionaryDTO, or with status 404 (Not Found)
     */
    @GetMapping("/dictionaries/{id}")
    @Timed
    public BaseDTO getDictionary(@PathVariable String id) {
        log.debug("REST request to get Dictionary : {}", id);
        DictionaryDTO dictionaryDTO = dictionaryService.findOne(id);
        return BaseDTO.createBaseDTO(dictionaryDTO);
    }

    /**
     * DELETE  /dictionaries/:id : delete the "id" dictionary.
     *
     * @param id the id of the dictionaryDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/dictionaries/{id}")
    @Timed
    public BaseDTO deleteDictionary(@PathVariable String id) {
        log.debug("REST request to delete Dictionary : {}", id);
        dictionaryService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("delete_success");
    }


}
